/*
 * 百度在线网络技术（北京）有限公司拥有本软件版权2021并保留所有权利。
 * Copyright 2021, Baidu.com,Inc 2:Baidu Online Network Technology (Beijing) Co.,Ltd,
 * All rights reserved.
 */

package com.azdebugit.singleton.exaple.反射也会对单例造成破坏;

import java.lang.reflect.Constructor;

public class Singleton {

    private static Singleton instance = new Singleton();

    private Singleton() {
    }

    public static Singleton getInstance() {
        return instance;
    }
//    Instance;
    public static void main(String[] args) {
        Singleton getInstance1 = Singleton.getInstance();
        Singleton getInstance2 = Singleton.getInstance();
        System.out.println("Is singleton pattern normally valid: " + (getInstance1 == getInstance2));
        try {
                   /* Class<Singleton> clazz = (Class<Singleton>) Class.forName("com.designpatterns.Singleton");
                    Constructor<Singleton> constructor = clazz.getConstructor(null); //获得无参构造函数*/
            Constructor<Singleton> constructor = Singleton.class.getDeclaredConstructor();
            constructor.setAccessible(true); //跳过权限检查，可以访问私有的构造函数
            Singleton refInstance3 = constructor.newInstance();
            System.out.println("Is single pattern valid for Reflection: " + (getInstance1 == refInstance3));
        } catch (Exception e) {
            e.printStackTrace();
        }

    }

}